package com.ktjy.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class AutoFilter implements Filter {
    private StringRedisTemplate stringRedisTemplate;

    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        //使用集合存储不过滤的请求名称
        Set<String> filterUrl = new HashSet<>();
        filterUrl.add("/");
        filterUrl.add("/doLogin");
        filterUrl.add("/logout");
        //判断用户是否登录
        if (session.getAttribute("loginUser") != null ||
                //判断请求是否再set集合中，如果再就不过滤
                filterUrl.contains(request.getServletPath()) ||
                //判断是不是以css结尾的请求，如果是就不过滤
                request.getServletPath().endsWith(".css") ||
                //判断是不是以ico结尾的请求，如果是就不过滤
                request.getServletPath().endsWith(".ico")) {
            if (stringRedisTemplate.opsForValue().get("loginUser")!=null && session.getAttribute("loginUser")==null){
                JSONObject jsonObject = (JSONObject) JSON.parse(stringRedisTemplate.opsForValue().get("loginUser"));
                session.setAttribute("loginUser",jsonObject );
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //重定向到登录页
            response.sendRedirect("/");
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
